<?php

namespace App\Libraries\Entities;

use App\Libraries\Contracts\IBaseModel;
use App\Libraries\Util\UuidHelper;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Libraries\Entities\BaseEntity.
 *
 * @mixin \Illuminate\Database\Eloquent\Model
 */
class BaseEntity extends Model implements IBaseModel
{
    public $timestamps = false;
    public $id;
    protected $primaryIsUuid = true;
    use HasEditEnable, HasSort, HasStatus, HasCreated, HasUpdated, HasDescription;

    public $incrementing = false;

    protected static function boot()
    {
        parent::boot();

        static::creating(function (BaseEntity $model) {
            $key = $model->getKeyName();
            if (empty($model->{$key})) {
                if ($model->primaryIsUuid) {
                    $model->{$key} = (string) $model->generateNewUuid();
                }
            }
        });
    }

    /**
     * @return \Ramsey\Uuid\UuidInterface
     *
     * @throws \Exception
     */
    public function generateNewUuid()
    {
        return UuidHelper::GenerateUuid();
    }

    public function primaryKeyIsUuid()
    {
        $id = $this[$this->primaryKey];

        return UuidHelper::IsUuid($id);
    }

    public function GetId()
    {
        return $this[$this->primaryKey];
    }

    public function getFillable()
    {
        $array = $this->fillable;
        if ($this->useStatus() && !in_array(static::STATUS, $array)) {
            array_push($array, static::STATUS);
        }
        if ($this->useEditEnable() && !in_array(static::EDIT_ENABLE, $array)) {
            array_push($array, static::EDIT_ENABLE);
        }
        if ($this->useDescription() && !in_array(static::DESCRIPTION, $array)) {
            array_push($array, static::DESCRIPTION);
        }
        if ($this->useSort() && !in_array(static::SORT, $array)) {
            array_push($array, static::SORT);
        }
        if ($this->useCreated()) {
            if (!in_array(static::CREATED_AT, $array)) {
                array_push($array, static::CREATED_AT);
            }
            if (!in_array(static::CREATED_USER_ID, $array)) {
                array_push($array, static::CREATED_USER_ID);
            }
        }
        if ($this->useUpdated()) {
            if (!in_array(static::UPDATED_USER_ID, $array)) {
                array_push($array, static::UPDATED_USER_ID);
            }
            if (!in_array(static::UPDATED_AT, $array)) {
                array_push($array, static::UPDATED_AT);
            }
        }
        $this->fillable($array);

        return $this->fillable;
    }

    public function ToBool($column)
    {
        return $this[$column] = 1 === $this[$column] ? true : false;
    }
}
